<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            Array.prototype.myCopyWithin = function (target = 0, begin = 0, end = this.length) {
                let arr = this;
                let len = arr.length;
                let copyArr = [];
                let m = 0,
                    n = 0;
                target = target >= 0 ? target : Math.abs(target) < len ? target + len : 0;
                begin = begin >= 0 ? begin : Math.abs(begin) < len ? begin + len : 0;
                end = end >= 0 ? Math.min(end, len) : Math.abs(end) < len ? end + len : end;
                // 把需要复制的元素放到 copyArr 数组中
                for (; begin < end; begin++) {
                    copyArr[m++] = arr[begin];
                }
                let _len = copyArr.length < len - target ? target + copyArr.length : len;
                // 用 copyArr 数组从 target 开始覆盖原数组
                for (; target < _len; target++) {
                    arr[target] = copyArr[n++];
                }
                return arr;
            };
            let arr = [1, 2, 3, 4, 5];
            arr.myCopyWithin(2, 0, 2);
            console.log(arr); // [1, 2, 1, 2, 5]
            let arr1 = [1, 2, 3, 4, 5];

            arr1.myCopyWithin(-2, -5, -3);
            console.log(arr1);
            let arr2 = [1, 2, 3, 4, 5];

            arr2.myCopyWithin(3, 1);
            console.log(arr2); // [1,1,2,3,4]
            let arr3 = [1, 2, 3, 4, 5];

            arr3.myCopyWithin(1, 0);
            console.log(arr3);
            let arr4 = [1, 2, 3, 4, 5];
            arr4.myCopyWithin(1, 3);
            console.log(arr4); // [1, 4, 5, 4, 5]
        </script>
    </body>
</html>
